// // 云函数入口文件
// const cloud = require('wx-server-sdk')

// cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境

// // 云函数入口函数
// exports.main = async (event, context) => {
//   const wxContext = cloud.getWXContext()

//   return {
//     event,
//     openid: wxContext.OPENID,
//     appid: wxContext.APPID,
//     unionid: wxContext.UNIONID,
//   }
// }


const cloud = require('wx-server-sdk');
const xlsx = require('xlsx');

cloud.init();



exports.main = async (event, context) => {
  const db = cloud.database();
  
  try {
    // 查询所有库存数据
    const res = await db.collection('items').get();
    const items = res.data;

    if (items.length === 0) {
      return { success: false, message: '暂无数据可导出' };
    }

    // 将数据转换为二维数组格式
    const data = [
      ['仓库', '物料号', '物料名称', '规格型号', '单位', '数量', '备注'], // 表头
      ...items.map(item => [
        item.warehouse,
        item.materialNumber,
        item.materialName,
        item.specification,
        item.unit,
        item.quantity,
        item.remark || '',
      ]),
    ];

    // 创建工作簿和工作表
    const worksheet = xlsx.utils.aoa_to_sheet(data);
    const workbook = xlsx.utils.book_new();
    xlsx.utils.book_append_sheet(workbook, worksheet, '库存数据');

    // 导出为二进制数据
    const excelBuffer = xlsx.write(workbook, { type: 'buffer', bookType: 'xlsx' });

    // 上传到云存储
    const fileName = `库存数据_${new Date().toISOString().slice(0, 10)}.xlsx`;
    const uploadRes = await cloud.uploadFile({
      cloudPath: fileName,
      fileContent: excelBuffer,
    });

    return {
      success: true,
      message: '导出成功',
      fileID: uploadRes.fileID,
    };
  } catch (err) {
    console.error(err);
    return { success: false, message: '导出失败，请稍后重试' };
  }
};